<?php

namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\Request;
use googauth\Googauth;

class GoogleAuth extends Adminbase
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $service = new Googauth();
        $google_secret = db('member')->where('id',$this->this_user['id'])->value('google_secret');
        if(empty($google_secret)){
            $secret = $service->createSecret();
            $urls = 'Mortal Admin';
            $img_url = $service->getQRCodeGoogleUrl($this->this_user['account'],$secret,$urls);
            $data['img'] = $img_url;
            $data['secret'] = $secret;
        }else{
            $data=[];
        }
        return view('index',['data'=>$data]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $data = $request->param();
        $google = isset($data['google_code']) ? $data['google_code'] : '';
        $google_secret = isset($data['google_secret']) ? $data['google_secret'] : '';
        if($google && $google_secret){
            $service = new Googauth;
            // 检查是否匹配
            if(!$service->verifyCode($google_secret, $google, 2)){
                return json(['code'=>1,'msg'=>'谷歌验证码错误']);
            }else{
                $info['google_secret'] = $google_secret;
                $res = db('member')->where('id',$this->this_user['id'])->update($info);
                if($res){
                    return json(['code'=>200,'msg'=>'绑定成功']);
                }else{
                    return json(['code'=>1,'msg'=>'绑定失败']);
                }
            }
        }else{
            return json(['code'=>1,'msg'=>'param error']);
        }
    }
}
